import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;


public class Main {

	public static void main(String[] args) throws Exception {	
		
		/*Pattern patSearch = Pattern.compile(".* ([0-9]+?) documents found.*");
		Matcher m = patSearch.matcher("asadsd 12 documents foundasdasd");
    	if(m.find()){
    		String strInt = m.group(1);
    		int tt = 0;
    		++tt;
    	}*/
		
		
		
		String configPath = "botConfig.xml";
		if(args.length > 0)
			configPath = args[0];
		BotConfig cfg = null;
		
		System.out.print("Biblio bot ver. 0.1 \n");
		
		XMLDecoder decoder = null;
		try
		{
			FileInputStream is = new FileInputStream(configPath);
			decoder = new XMLDecoder(is);
			cfg = (BotConfig)decoder.readObject();
		}
		catch (Exception e) {
			System.err.print(e.getMessage());
			System.err.print("\n");
		}
		finally
		{			
			if(decoder != null)
				decoder.close();
		}
		if(cfg == null)
		{
			XMLEncoder encoder = null;
			try
			{
				cfg = new BotConfig();
				cfg.MakeDefaults();
				FileOutputStream os = new FileOutputStream(configPath);
				encoder = new XMLEncoder(os);
				encoder.writeObject(cfg);
			}
			catch (Exception e) {
			}
			finally
			{
				if(encoder != null)
					encoder.close();
			}
			System.out.print("Brak pliku konfiguracji...");
			return;
		}
		ArrayList<Engine> engines = new ArrayList<Engine>();
		try
		{
			if(cfg.isCiteseerx())
				engines.add(new Engine(cfg, new citeseerxEngine(cfg)));
			if(cfg.isDblp())
				engines.add(new Engine(cfg, new dblpEngine(cfg)));
			if(cfg.isScholar())
				engines.add(new Engine(cfg, new scholarEngine(cfg)));
			if(cfg.isGooglePat())
				engines.add(new Engine(cfg, new googlePat(cfg)));
			if(cfg.isEspacenet())
				engines.add(new Engine(cfg, new espacenet(cfg)));
			
			for (Engine engine : engines) {
				new Thread(engine).start();
			}
			
			System.in.read();
			
			for (Engine engine : engines) {
				engine.stop();
			}			
			for (Engine engine : engines) {
				while(engine.isEnd() == false)
					Thread.sleep(500);
			}
		}
		catch (Exception e) {
			System.out.print(e.getMessage());
			System.err.print("\n");
		}
			
	}

}
